import { useEffect, useState } from 'react'
import { getUserListBySearch } from '@/api/user'
import { getAreaById, getAreaByType } from '@/api'
export interface IAreaType {
  comments: string
  id: number
  joinCode: string
  level: number
  locCode: string
  recStatus: string
  superior: number
}
export interface IOptionArea {
  value: string | number
  label: string
  children?: IOptionArea[]
  isLeaf?: boolean
}

const useGetArea = (areaList?: number[]) => {
  const [AreaOptions, setAreaOptions] = useState<IOptionArea[]>([])
  useEffect(() => {
    getProductClassConfig()
  }, [])
  const loadAreaData = async (selectedOptions: IOptionArea[]) => {
    const targetOption = selectedOptions[selectedOptions.length - 1]
    if (targetOption?.value === undefined) return
    const res = await getAreaById<IAreaType>(targetOption?.value)
    if (res.code === 200) {
      const childrenOption = handleChildren(res.data)
      targetOption.children = childrenOption
      const deepAreaOptions = JSON.parse(JSON.stringify(AreaOptions))
      setAreaOptions(deepAreaOptions)
      return deepAreaOptions
    }
  }
  useEffect(() => {
    if (areaList && areaList.length > 0 && AreaOptions.length > 0) {
      backShow(areaList)
    }
  }, [areaList])
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 2) => {
    const res = await getAreaByType<{
      comments: string
      id: string | number
    }>(type)
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.comments,
          value: item.id,
          isLeaf: false,
        }
      }) || []
    setAreaOptions([...classIdOptions])
  }
  const handleChildren = (arr: IAreaType[]): IOptionArea[] => {
    return arr?.map((item) => {
      return {
        label: item.comments,
        value: item.id,
        isLeaf: arr?.[0]?.level === 4 ? true : false,
      }
    })
  }
  const backShow = async (areaList: number[]) => {
    const provinceId = areaList[0]
    const selectedOptions = AreaOptions?.filter((item) => item.value === provinceId)
    await loadAreaData(selectedOptions)
    const cityId = areaList[1]
    const selectedOptionCityChildren = selectedOptions[0]?.children || []
    const selectedOptionCity = selectedOptionCityChildren?.filter((item) => item.value === cityId)
    await loadAreaData(selectedOptionCity)
  }
  return { AreaOptions, setAreaOptions, loadAreaData }
}

export default useGetArea
